package com.ithailong.reconsitutionmassion.controller;

import com.ithailong.reconsitutionmassion.dao.Impl.FileDaoImpl;
import com.ithailong.reconsitutionmassion.entity.FileModel;
import com.ithailong.reconsitutionmassion.entity.Page;
import com.ithailong.reconsitutionmassion.entity.User;
import com.ithailong.reconsitutionmassion.service.Impl.FileServiceImpl;
import com.ithailong.reconsitutionmassion.util.ConstantMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * author:hlc
 * date:2023/10/30
 *
 * @author 17930
 */
@Controller
public class FileController {
   @Autowired
   private FileServiceImpl fileService;
   @Autowired
   private FileDaoImpl fileDao;

   @Value("${my.base.path}")
   private String basePath;

   @GetMapping("/selectAllFile")
   public ModelAndView selectAllFile(@RequestParam(value = "p", defaultValue = "1") int pageNum,
                                     @RequestParam(value = "s", defaultValue = "8") int pageSize,
                                     FileModel fileModel) {
      List<FileModel> fileModels = fileService.selectAllFile(pageNum, pageSize, fileModel);
      int total = fileService.selectTotal(fileModel);
      Page page = new Page(pageNum, pageSize, total, fileModels);
      ModelAndView mv = new ModelAndView();
      mv.setViewName("fileList");
      mv.addObject("search", fileModel);
      mv.addObject("fileList", page);
      return mv;
   }

   @GetMapping("/uploadFile")
   public String uploadFile() {
      return "uploadPage";
   }

   @PostMapping("/upload")
   public String upload(@RequestParam("fileToUpload") MultipartFile file, RedirectAttributes attributes, User user) throws IOException {
      fileService.saveFile(file, user);
      if (user == null) {
         return "redirect:/selectAllFile";
      } else {
         attributes.addFlashAttribute("success", "修改成功");
         return "redirect:/person";
      }
   }

   @GetMapping("/download{downloadLink}")
   public void downloadFile(String downloadLink, HttpServletRequest request, RedirectAttributes attributes, HttpServletResponse response) throws IOException {
      System.out.println(downloadLink + "========");
      String replace = "/upload/";
      String replace1 = downloadLink.replace(replace, "");
      //设置响应头可以下载   设置下载的文件名称
      String encodedFilename = URLEncoder.encode(replace1, "UTF-8");
      response.setHeader("content-Disposition", "attachment;filename=" + encodedFilename);
      System.out.println(encodedFilename);
      //找到本地文件
      File file = new File(basePath, replace1);
      try (FileInputStream fis = new FileInputStream(file);) {
         fis.transferTo(response.getOutputStream());
      } catch (FileNotFoundException e) {
         response.setContentType("text/plain;charset=utf-8");
         response.getWriter().println("未找到文件");
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   @GetMapping("/deleteFile/{id}")
   public String deleteFile(@PathVariable("id") Integer id, RedirectAttributes attributes) {
      fileDao.deleteFile(id);
      attributes.addFlashAttribute("message", "删除成功");
      return "redirect:/selectAllFile";
   }

   @GetMapping("/toFileList")
   public String toFileList(Model model) {
      File file = new File(ConstantMessage.BASE_PATH);
      ArrayList<FileModel> directory = fileService.isDirectory(file);
      model.addAttribute("fileList", directory);
      System.out.println(directory.size());
      return "fileListFile";
   }

   @GetMapping("/lookFile/**")
   public void lookFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
      String requestURI = request.getRequestURI();
      System.out.println(requestURI);
      boolean download = requestURI.contains("download");
      if (download) {
         System.out.println(download);

         String s1 = requestURI.replaceAll("&download.*", "");
         String s = s1.replaceAll("/lookFile", "");
         String encodedFilename = URLEncoder.encode(s, "UTF-8");
         File file = new File(ConstantMessage.BASE_PATH, encodedFilename);
         if (file.exists()) {
            try (FileInputStream fis = new FileInputStream(file)) {
               if (download) {
                  response.setHeader("content-Disposition", "attachment;filename=" + file.getName());
               }
               response.setContentType("application/octet-stream");
               StreamUtils.copy(fis, response.getOutputStream());
            } catch (FileNotFoundException e) {
               response.setContentType("text/plain;charset=utf-8");
               response.getWriter().println("未找到文件");
               e.printStackTrace();
            } catch (IOException e) {
               throw new RuntimeException(e);
            }
         } else {
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().println("未找到文件");
         }
      } else {
         String s1 = requestURI.replaceAll("&download.*", "");
         String s = s1.replaceAll("/lookFile", "");//  /20231026/131e2a43d0ba4d8a9730c0f25bce2acb.jpg
         File file = new File(ConstantMessage.BASE_PATH, s);
         try (FileInputStream fis = new FileInputStream(file);) {
            fis.transferTo(response.getOutputStream());
         } catch (FileNotFoundException e) {
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().println("未找到文件");
            e.printStackTrace();
         } catch (IOException e) {
            throw new RuntimeException(e);
         }
      }
   }
}
